<template>
  <!-- <div> -->
  <template
    v-if="
      hasOneShowingChild(item.children, item) &&
      (!onlyOneChild.children || onlyOneChild.noShowingChildren)
    "
  >
    <el-menu-item :index="item.viewPath">
      <template #title>
        <i :class="item.icon"></i>
        <span>{{ item.name }}</span>
      </template>
    </el-menu-item>
  </template>
  <el-submenu v-else :index="item.viewPath">
    <template #title>
      <i :class="item.icon"></i>
      <span>{{ item.name }}</span>
    </template>

    <template v-for="child in item.children">
      <sidebar-item
        v-if="child.children && child.children.length > 0"
        :item="child"
        :key="child.viewPath"
        :base-path="child.viewPath"
      />
      <el-menu-item v-else :key="child.viewPath" :index="child.viewPath">
        <span>{{ child.name }}</span>
      </el-menu-item>
    </template>
  </el-submenu>
  <!-- </div> -->
</template>

<script>
import { ref, reactive, toRefs } from "vue";

export default {
  name: "SidebarItem",
  props: {
    item: {
      type: Object,
      required: true,
    },
    basePath: {
      type: String,
      default: "",
    },
  },
  setup() {
    const state = reactive({
      onlyOneChild: null,
    });

    const hasOneShowingChild = (children = [], parent) => {
      const showingChildren = children.filter((item) => {
        if (item.hidden) {
          return false;
        } else {
          // Temp set(will be used if only has one showing child)
          state.onlyOneChild = item;
          return true;
        }
      });

      // When there is only one child router, the child router is displayed by default
      // if (showingChildren.length === 1) {
      //   return true
      // }
      // Show parent if there are no child router to display
      if (showingChildren.length === 0) {
        state.onlyOneChild = { ...parent, path: "", noShowingChildren: true };
        return true;
      }

      return false;
    };

    // const resolvePath = (path, parentPath) => {
    //   if (path == "home") {
    //     return "/" + path;
    //   }
    //   if (parentPath) {
    //     return parentPath + "/" + path;
    //   } else {
    //     return path;
    //   }
    // };

    return {
      ...toRefs(state),
      hasOneShowingChild,
    };
  },
};
</script>
